import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/pages/common/report/reportsStudentPersonalContent.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/charts/classskill.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:toggle_switch/toggle_switch.dart';

class ReportsStudentPersonalSkill extends StatefulWidget {
  ReportsStudentPersonalSkill({
    Key? key,
    required this.userName,
  }) : super(key: key);
  final String userName;

  @override
  ReportsStudentPersonalSkillState createState() =>
      ReportsStudentPersonalSkillState();
}

class ReportsStudentPersonalSkillState
    extends State<ReportsStudentPersonalSkill> {
  final ReportsController _reportsController = Get.find();
  var box = Hive.box('appconfig');
  final form = FormGroup({
    'to': FormControl<DateTime>(validators: [Validators.required]),
  });

  var endTime;
  bool isFirstAttempt = false;

  @override
  void initState() {
    studentPersonalReportTab = Constants.studentPersonalReportTabs[1];

    form.control('to').value = null;
    Future.delayed(Duration(milliseconds: 300), () {
      fetchOverallData(endTime, isFirstAttempt);
    });
    super.initState();
  }

  void fetchData(String userName) {
    Future.delayed(Duration(milliseconds: 300), () {
      _reportsController.fetchStudentSkillsByUsername(
          userName, endTime, isFirstAttempt);
    });
  }

  void _onCustomTimeUpdate() {
    if (!form.valid) {
      form.markAllAsTouched();
      return;
    } else {
      var tempEndTime =
          form.control("to").value.millisecondsSinceEpoch.toString();
      setState(() {
        endTime = tempEndTime;
      });
      fetchOverallData(tempEndTime, isFirstAttempt);
    }
  }

  void _onCustomTimeClear() {
    form.control("to").value = null;
    setState(() {
      endTime = null;
    });
    fetchOverallData(null, isFirstAttempt);
  }

  void fetchOverallData(endTime, isFirstAttempt) {
    _reportsController.fetchStudentSkillsByUsername(
        widget.userName, endTime, isFirstAttempt);
  }

  void _onToggle(value) {
    setState(() {
      isFirstAttempt = value;
    });
    fetchOverallData(endTime, isFirstAttempt);
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build SchoolAdmin reportsStudentPersonal Skill');
    return SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Container(
                  width: 350,
                  child: ReactiveForm(
                    formGroup: form,
                    child: Row(
                      children: <Widget>[
                        Flexible(
                          flex: 6,
                          child: ReactiveTextField<DateTime>(
                            formControlName: 'to',
                            decoration: InputDecoration(
                              suffixIcon: ReactiveDatePicker<DateTime>(
                                formControlName: 'to',
                                firstDate: DateTime(1990),
                                lastDate: DateTime.now(),
                                builder: (context, picker, child) {
                                  return IconButton(
                                    onPressed: picker.showPicker,
                                    icon: const Icon(Icons.date_range),
                                  );
                                },
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 21.0),
                          child: ReactiveFormConsumer(
                            builder: (context, form, child) {
                              return ElevatedButton(
                                  child: Text('Go'.tr),
                                  onPressed: _onCustomTimeUpdate);
                            },
                          ),
                        ),
                        ReactiveFormConsumer(
                          builder: (context, form, child) {
                            return ElevatedButton(
                                child: Text('Clear'.tr),
                                onPressed: _onCustomTimeClear);
                          },
                        ),
                      ],
                    ),
                  )),
            ],
          ),
          Padding(
            padding: const EdgeInsets.only(top: 21.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ToggleSwitch(
                  customWidths: [130.0, 140.0],
                  minHeight: 30.0,
                  cornerRadius: 3.0,
                  activeBgColors: [
                    [Get.theme.primaryColor]
                  ],
                  activeFgColor: Get.isDarkMode
                      ? Colors.black
                      : Get.theme.primaryColorLight,
                  inactiveBgColor:
                      Get.isDarkMode ? Get.theme.primaryColor : Colors.blueGrey,
                  inactiveFgColor: Get.isDarkMode
                      ? Colors.black
                      : Get.theme.primaryColorLight,
                  totalSwitches: 2,
                  initialLabelIndex: 0,
                  labels: ['Overall', 'First Attempt'],
                  onToggle: (index) {
                    Log.debug('switched to: $index');
                    _onToggle(index == 1);
                  },
                ),
                // Container(
                //   decoration: BoxDecoration(
                //     color: Get.isDarkMode
                //         ? AppTheme.colors.darkTheme2
                //         : Colors.white.withOpacity(0.3),
                //   ),
                //   margin: EdgeInsets.only(left: 30.0, top: 12.0),
                //   padding: const EdgeInsets.symmetric(
                //       horizontal: 21.0, vertical: 12.0),
                //   child: Text(
                //     isFirstAttempt ? "First Attempt".tr : "Overall".tr,
                //     style: TextStyle(
                //       fontSize: 15.0,
                //       letterSpacing: 1.0,
                //       color: Get.isDarkMode
                //           ? Get.theme.primaryColorDark
                //           : Colors.black.withOpacity(0.6),
                //     ),
                //   ),
                // ),
                Container(
                  padding: EdgeInsets.all(21.0),
                  width: double.infinity,
                  height: 450,
                  child: Obx(() {
                    if (_reportsController.studentSkillData.isNotEmpty)
                      return AnimationClassSkillWidget(
                        skillchartData: _reportsController.studentSkillData,
                        title: "${widget.userName} skills",
                      );
                    else
                      return Text('Data not available ...'.tr);
                  }),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
